package kr.pe.johnkim.sendme.activity;

import java.util.ArrayList;

import kr.pe.johnkim.sendme.activity.SendMeSubSettingsMessageAlarmActivity.backgroundThreadSaveMessageAlarm;
import kr.pe.johnkim.sendme.provider.SendMeInstall;
import kr.pe.johnkim.sendme.provider.SendMeMember;
import kr.pe.johnkim.sendme.provider.SendMeVoice;
import kr.pe.johnkim.sendme.rest.SendMeAudioMessageRest;
import kr.pe.johnkim.sendme.rest.SendMeInstallRest;
import kr.pe.johnkim.sendme.rest.SendMeMemberRest;
import kr.pe.johnkim.sendme.util.SendMeCommon;
import kr.pe.johnkim.sendme.util.SendMeConstant;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.sun.mail.dsn.message_deliverystatus;

/**
 * GCM 관련된 기능을 구현하는 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class GCMIntentService extends GCMBaseIntentService {
	
	public static String TAG = GCMIntentService.class.getSimpleName();
	
	// 메시지 알림 설정 값
	private static final int MESSAGE_ALARM_METHOD_SOUND = 1;			// 소리
	private static final int MESSAGE_ALARM_METHOD_VIBRATION = 2;		// 진동
	private static final int MESSAGE_ALARM_METHOD_NOTHING = 3;			// 무음
	
	// 사운드 선택
	private static final int MESSAGE_ALARM_SOUND_TYPE_DEFAULT = 1;			// 기본 알림음
	private static final int MESSAGE_ALARM_SOUND_TYPE_A = 2;			// 소리 A
	private static final int MESSAGE_ALARM_SOUND_TYPE_B = 3;			// 소리 B
	
	
	
	// Push id for GCM.
	private String PUSH_ID = "";
	
	// 사용자 휴대 전화번호.
	private String PHONE_NUMBER = "";
		
	private static final int THREAD_UPDATE_PUSH_ID = 101;
	// 소리 재생
	private static final int THREAD_PLAY_SOUND_DEFAULT = 102;	 // 기본
	private static final int THREAD_PLAY_SOUND_TYPE_A = 103;	 // 1
	private static final int THREAD_PLAY_SOUND_TYPE_B = 104;	 // 2
	
	int soundNum;
	/*
	 * 알람 수신 관련 설정
	 */
	boolean  isToggleButtonMessageReceiveOn;
	boolean  isToggleButtonMessagePopUpOn;
	int checkedRadioGroupMessageAlarmMethod;
	// 진동
	Vibrator Vi;	
	int vibrateCnt = 3;	// n 회 진동
	// 사운드
	SoundPool soundPool;
	int[] sound;  

	
	public GCMIntentService()  {
		super(SendMeConstant.PROJECT_NUMBER);
	}

	/**
	 * 오류 발생시 오류 메시지를 받는다.
	 */
	@Override
	protected void onError(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onError message : " + arg1);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.i(TAG, "Received message");
		Vi= (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
		Log.d(TAG,"getExtras ::"+intent.getExtras());				
		// getExtras ::Bundle[{MESSAGE=NEW_VOICE, collapse_key=do_not_collapse, from=983190139288}]
		String message = intent.getStringExtra("MESSAGE");
		
		
		// 뱃지 업데이트
		showBadgeUnreadCount();
		
		
		// notifies user
		generateNotification(context, message);	// 추가 작업. 
	}

	/**
	 * GCM 등록 id 를 받는다.
	 * 설정 파일에 저장 한다.
	 */
	@Override
	protected void onRegistered(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		
		Log.i(TAG, "onRegistered id : " + arg1);
		
		confirmNotification();	// 저장된 pushId, 전화번호를 꺼낸다.
		
		if(PUSH_ID.equals(arg1)){
			Log.d(TAG,"pushId not changed");
		}else{
			PUSH_ID = arg1;	
			// 저장
			mHandler.sendMessage(mHandler.obtainMessage(THREAD_UPDATE_PUSH_ID));
		}
	}

	/**
	 * GCM 등록 해지 id 를 받는다.
	 */
	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onUnregistered id : " + arg1);
	}
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	/**
	 * 필요한 핸들러를 등록해서 사용한다.
	 */
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			// push id 를 업데이트 한다.
			case THREAD_UPDATE_PUSH_ID : 
				threadUpdatePushId();
				break;
				
				// 소리 재생
			case THREAD_PLAY_SOUND_DEFAULT : 
				threadPlaySoundDefault();
				break;
			case THREAD_PLAY_SOUND_TYPE_A : 
				threadPlaySoundTypeA();
				break;
			case THREAD_PLAY_SOUND_TYPE_B : 
				threadPlaySoundTypeB();
				break;
				
			}
		}
	};
	/**
	 * push id 를 업데이트 한다.
	 */
	public void threadUpdatePushId() {

		Thread thread = new Thread(new Runnable() {

			public void run() {
				
				SendMeCommon sendMeCommon = new SendMeCommon();
				String nowTime = sendMeCommon.getCurrentDate();
				
				// TODO Auto-generated method stub
				SendMeMemberRest sendMeMemberRest = new SendMeMemberRest();		
				
				SendMeMember sendMeMember = new SendMeMember();
				sendMeMember.setPhoneNumber(PHONE_NUMBER);
				sendMeMember.setPushId(PUSH_ID);
				sendMeMember.setActivateYn("Y");
				sendMeMember.setModifyDate(nowTime);
				
				SendMeMember result = sendMeMemberRest.updatePushId(sendMeMember);
				if(result.getResult().equals("SUCCESS")){
					// 전화번호를 설정파일에 저장 한다.
					SharedPreferences sharedPreferences = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
					SharedPreferences.Editor editor = sharedPreferences.edit();
					editor.putString("push_id", PUSH_ID);
					editor.commit();
					
					Log.d(TAG,"save push_id Success");
				}
			}
		});
		thread.start();
	}
	
	

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// notification
	
	
	/*
	 * 사용자에게 노티 알림을 띄운다 
	 */
	public void generateNotification(Context context, String message){
		//		int icon = R.drawable.ic_launcher;
//		vibrateOneTimes();
		
		// 값유지가 안되서 매번 호출해준다.
		selectPreferenceMessageAlarmData();
		
		if(isToggleButtonMessageReceiveOn){		// 알람을 받는 경우에만 진행.
			if(isToggleButtonMessagePopUpOn){		// 팝업
				// 미구현..
			}
			switch(checkedRadioGroupMessageAlarmMethod){
				case MESSAGE_ALARM_METHOD_SOUND:
					if(soundNum == MESSAGE_ALARM_SOUND_TYPE_A){
						mHandler.sendMessage(mHandler.obtainMessage(THREAD_PLAY_SOUND_TYPE_A));
					}else if(soundNum ==MESSAGE_ALARM_SOUND_TYPE_B){
						mHandler.sendMessage(mHandler.obtainMessage(THREAD_PLAY_SOUND_TYPE_B));
					}else{
						mHandler.sendMessage(mHandler.obtainMessage(THREAD_PLAY_SOUND_DEFAULT));
					}
				break;
			case MESSAGE_ALARM_METHOD_VIBRATION:
				vibrateOneTimes();
				break;
			case MESSAGE_ALARM_METHOD_NOTHING:
				break;
			}
			
			
			Log.d(TAG,"message::"+message);
			
			// 보여줄 메시지 결정
			String contents = "";
			if(message.equals("NEW_VOICE")){		
				contents =  "새로운 메시지가 도착하였습니다.";			
			}else{
				contents =  message;		
			}

			///////////////////////
//			Intent notificationIntent = new Intent(context, SendMeIntroActivity.class);	// *** // 터치시 실행될 액티비티인가봉가
			Intent notificationIntent = new Intent(context, SendMeLauncherActivity.class);	// *** // 터치시 실행될 액티비티인가봉가

			// 공통부
			PendingIntent contentIntent = PendingIntent.getActivity(context,
					0, notificationIntent,
					PendingIntent.FLAG_CANCEL_CURRENT);
			NotificationManager nm = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			Resources res = context.getResources();
			Builder builder = new Builder(context);
			builder.setContentIntent(contentIntent)
			.setSmallIcon(R.drawable.ic_launcher)		// 우측 하단 작은 이미지.. -- 주석하니까 안나옴
			.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))		// 왼쪽 왕큰 이미지
			.setTicker(res.getString(R.string.app_name))
			.setWhen(System.currentTimeMillis())
			.setAutoCancel(true)		// 기본. 터치시 액티비티 실행하고 종료됨.
//			.setAutoCancel(false)		// 건드리는거로 종료되지 않음. 지우기 로는 지워짐.
			.setContentTitle(res.getString(R.string.app_name))
			.setContentText(contents);	// *** 
			Notification n = builder.build();
			nm.notify(0, n);
			
		}

	}
	
	
	/**
	 * 뱃지 카운트 설정한다
	 *   삼성 런처에서만 된다..
	 */
	public void showBadgeUnreadCount(){
		Log.d(TAG,"showBadgeUnreadCount");
		new backgroundThreadSelectUnreadVoiceCount().execute();
	}
	
	/**
	 * backgroundThreadSelectUnreadVoiceCount
	 * 비동기  .  설정에 이름 저장
	 * @author blue
	 *
	 */
	public class backgroundThreadSelectUnreadVoiceCount extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadSelectUnreadVoiceCount");
			
			confirmNotification();
			
			SendMeAudioMessageRest sendMeAudioMessageRest = new SendMeAudioMessageRest();
			
			SendMeVoice sendMeVoice = new SendMeVoice();
			sendMeVoice.setReceiver(PHONE_NUMBER);
			
			int unReadCount = sendMeAudioMessageRest.selectUnreadVoiceCount(sendMeVoice);
			
			SendMeCommon sendMeCommon = new SendMeCommon();
			// 안읽은 메시지 개수 증가
			
			Log.d(TAG,"unReadCount::"+unReadCount);
			sendMeCommon.badgeCountPrefSave(returnThis(), unReadCount);
			// 뱃지 업데이트
			sendMeCommon.badgeCountAutoSet(returnThis());
			
			// 화면이 열려있다면 적용
			try{
				if(selectPrefReceiveMessageListOpened()){
					// 열려있으면 바로 업데이트.			
					SendMeReceiveVoiceListActivity sendMeReceiveVoiceListActivity = (SendMeReceiveVoiceListActivity)SendMeReceiveVoiceListActivity.sendMeReceiveVoiceListActivityForUpdate;
					if(sendMeReceiveVoiceListActivity!=null){
						sendMeReceiveVoiceListActivity.callSelectMessageList();	
					}else{
						// 액티비티 닫혔다고 업뎃.
						savePrefReceiveMessageListClosed();
					}
				}else if(selectPrefMainOpened()){		
					SendMeMainActivity sendMeMainActivity = (SendMeMainActivity)SendMeMainActivity.sendMeMainActivityForUpldate;
					if(sendMeMainActivity!=null){
						sendMeMainActivity.onResume();
					}else{
						// 액티비티 닫혔다고 업뎃.
						savePrefMainClosed();
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return null; 
		}
	}
	
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 진동 및 소리 알림
	

	// 진동 1
	public void vibrateOneTimes(){
		new Thread(
				new Runnable(){
					public void run(){
						try {
							Vi.vibrate(1000);
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
		).start();
	}
	// 진동 3
	public void vibrateNTimes(){
		new Thread(
				new Runnable(){
					public void run(){
						try {
							for(int i=0; i<vibrateCnt; i++){
								Vi.vibrate(1000);
								Thread.sleep(2000);
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
		).start();
	}
		
	
	/**
	 * threadPlaySoundDefault
	 *  소리 재생 - default
	 */
	public void threadPlaySoundDefault() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(),RingtoneManager.TYPE_NOTIFICATION);
					Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
					ringtone.play();
				} catch (Exception e) {
					Log.d(TAG,"soundPool err. play default sound");
				}
			}
		});
		thread.start();
	}
	/**
	 * threadPlaySoundTypeA
	 *  소리 재생 - A
	 */
	public void threadPlaySoundTypeA() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					if(soundPool==null){
						Log.d(TAG,"create new soundPool");
						soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0 );		
						soundNum =  soundPool.load(returnThis(), R.raw.bip, 1);
						
						soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
							@Override
							public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
								soundPool.play(soundNum, 1, 1, 0, 0, 1);	
							}
						});						
					}else{
						Log.d(TAG,"reuse soundPool");
						soundPool.play(soundNum, 1, 1, 0, 0, 1);	
					}
				} catch (Exception e) {
					Log.d(TAG,"soundPool err. play default sound");
					Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(),RingtoneManager.TYPE_NOTIFICATION);
					Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
					ringtone.play();
				}
			}
		});
		thread.start();
	}
	/**
	 * threadPlaySoundTypeB
	 *  소리 재생 - B
	 */
	public void threadPlaySoundTypeB() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					if(soundPool==null){
						Log.d(TAG,"create new soundPool");
						soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0 );		
						soundNum =  soundPool.load(returnThis(), R.raw.computer_magic_microsift, 1);
						
						soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
							@Override
							public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
								soundPool.play(soundNum, 1, 1, 0, 0, 1);	
							}
						});						
					}else{
						Log.d(TAG,"reuse soundPool");
						soundPool.play(soundNum, 1, 1, 0, 0, 1);	
					}
				} catch (Exception e) {
					Log.d(TAG,"soundPool err. play default sound");
					Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(),RingtoneManager.TYPE_NOTIFICATION);
					Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
					ringtone.play();
				}
			}
		});
		thread.start();
	}
	
	public Context returnThis(){
		return this;
	}
		
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	
	
	
	/**
	 * SharedPreference 푸시 정보를 확인 한다.
	 */
	public void confirmNotification() {
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		
		PUSH_ID = mSharedPreference.getString("push_id", "");
		PHONE_NUMBER = mSharedPreference.getString("phone_number", "");
	}
	
	/**
	 * SharedPreference 알람 정보를 확인 한다.
	 */
	public void selectPreferenceMessageAlarmData() {
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		isToggleButtonMessageReceiveOn = mSharedPreference.getBoolean("setting_message_receive_on", true);
		Log.d(TAG,"isToggleButtonMessageReceiveOn::"+isToggleButtonMessageReceiveOn);
		isToggleButtonMessagePopUpOn  = mSharedPreference.getBoolean("setting_message_popup_on", true);
		Log.d(TAG,"isToggleButtonMessagePopUpOn::"+isToggleButtonMessagePopUpOn);
		checkedRadioGroupMessageAlarmMethod  = mSharedPreference.getInt("setting_message_alarm_method", 2);
		Log.d(TAG,"checkedRadioGroupMessageAlarmMethod::"+checkedRadioGroupMessageAlarmMethod);
		soundNum = mSharedPreference.getInt("setting_message_alarm_method_sound", 1);
		Log.d(TAG,"soundNum::"+soundNum);
	}
	
	
	/**
	 * SharedPreference 상태를 확인한다 (받은 메시지 리스트 열림)
	 *  푸시 받아서 업데이트 용도
	 */
	public boolean selectPrefReceiveMessageListOpened() {
		Log.d(TAG,"selectPrefReceiveMessageListOpened");
		boolean openedYn = false;
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		openedYn = mSharedPreference.getBoolean("receive_message_list_open_yn", false);
		return openedYn;
	}
	/**
	 * SharedPreference 상태를 확인한다 (메인 화면 열림)
	 *  푸시 받아서 업데이트 용도
	 */
	public boolean selectPrefMainOpened() {		
		Log.d(TAG,"selectPrefMainOpened");
		boolean openedYn = false;
		SharedPreferences mSharedPreference = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		openedYn = mSharedPreference.getBoolean("main_open_yn", false);
		return openedYn;
	}
	
	
	
//	/**
//	 * 설정파일에 저장한다
//	 */
//	public void savePreferenceMessageAlarmData() {
//		try{
//			SharedPreferences sharedPreferences = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
//			SharedPreferences.Editor editor = sharedPreferences.edit();
//			editor.putBoolean("setting_message_receive_on", isToggleButtonMessageReceiveOn);
//			editor.putBoolean("setting_message_popup_on", isToggleButtonMessagePopUpOn);
//			editor.putInt("setting_message_alarm_method", checkedRadioGroupMessageAlarmMethod);
//			editor.commit();
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//	}
	
	/**
	 * SharedPreference 에 상태를 저장한다 (받은 메시지 리스트 닫힘)
	 *  푸시 받아서 업데이트 용도
	 */
	public void savePrefReceiveMessageListClosed() {
		// 저장
		SharedPreferences sharedPreferences = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putBoolean("receive_message_list_open_yn", false);
		editor.commit();
	}
	/**
	 * SharedPreference 에 상태를 저장한다 (받은 메시지 리스트 닫힘)
	 *  푸시 받아서 업데이트 용도
	 */
	public void savePrefMainClosed() {
		// 저장
		SharedPreferences sharedPreferences = getSharedPreferences(SendMeConstant.SENDME_PREFERENCE, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putBoolean("main_open_yn", false);
		editor.commit();
	}

}
